package com.medical.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.medical.entity.User;
import com.medical.service.UserService;

@Controller
@RequestMapping("/open")
public class OpenController {
	
	@Autowired
	private UserService biz;
	
	@GetMapping("/toOpenId")
	 public String getOpenId(String code,HttpServletResponse res,Model model) throws IOException{
	     String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1a3f8421d472017b&secret=671884725628e6c7b69faefde2eb19e5&code="+code+"&grant_type=authorization_code";
	     String openId="";
	            try {
	                URL getUrl=new URL(url);
	                HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                InputStream is = http.getInputStream(); 
	                int size = is.available(); 
	                byte[] b = new byte[size];
	                is.read(b);
	    
	    
	                String message = new String(b, "UTF-8");
	    
	                JSONObject json = JSONObject.parseObject(message);
	                
	                openId = json.getString("openid");
	                if(openId==null) {
	                	return "login-fail";
	                }
	                String access_token=json.getString("access_token");
	                //int count=biz.updateOpenId(userId, openId);
	                url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
	                getUrl=new URL(url);
	                http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                is = http.getInputStream(); 
	                size = is.available(); 
	                b = new byte[size];
	                is.read(b);
	    
	    
	                message = new String(b, "UTF-8");
	                json = JSONObject.parseObject(message);
	                System.out.println(json.toJSONString());
	                String nickname=json.getString("nickname");
	                String headimgurl=json.getString("headimgurl");
	                Boolean sex=json.getBoolean("sex");
	                User user=biz.getById(openId);
	                if(user!=null) {
		                if(user.getName()==null||user.getName().equals("")) {
		                	user.setNickname(nickname);
		                }
		                if(user.getSex()==null) {
		                	user.setSex(sex);
		                }
		                if(user.getPortrait()==null||user.getPortrait().equals("")) {
		                	user.setPortrait(headimgurl);
		                }
		                biz.updateUsers(user);
	                }else {
	                	user=new User();
	                	user.setNickname(nickname);
	                	user.setSex(sex);
	                	user.setPortrait(headimgurl);
	                	user.setOpenid(openId);
	                	biz.addUser(user);
	                }
	                model.addAttribute("openId", openId);
	                } catch (MalformedURLException e) {
	                    e.printStackTrace();
	                    return "login-fail";
	                } catch (IOException e) {
	                    e.printStackTrace();
	                    return "login-fail";
	                }catch (Exception e) {
						// TODO: handle exception
	                	return "login-user";
					}
	            return "tiao";
	    }
	
	@GetMapping("/toOpenIdByUser")
	 public String toOpenIdByUser(String code,HttpServletResponse res,Model model) throws IOException{
	     String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1a3f8421d472017b&secret=671884725628e6c7b69faefde2eb19e5&code="+code+"&grant_type=authorization_code";
	     String openId="";
	            try {
	                URL getUrl=new URL(url);
	                HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                InputStream is = http.getInputStream(); 
	                int size = is.available(); 
	                byte[] b = new byte[size];
	                is.read(b);
	    
	    
	                String message = new String(b, "UTF-8");
	    
	                JSONObject json = JSONObject.parseObject(message);
	                
	                openId = json.getString("openid");
	                if(openId==null) {
	                	return "login-user";
	                }
	                String access_token=json.getString("access_token");
	                //int count=biz.updateOpenId(userId, openId);
	                url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
	                getUrl=new URL(url);
	                http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                is = http.getInputStream(); 
	                size = is.available(); 
	                b = new byte[size];
	                is.read(b);
	    
	    
	                message = new String(b, "UTF-8");
	                json = JSONObject.parseObject(message);
	                System.out.println(json.toJSONString());
	                String nickname=json.getString("nickname");
	                String headimgurl=json.getString("headimgurl");
	                Boolean sex=json.getBoolean("sex");
	                User user=biz.getById(openId);
	                if(user!=null) {
		                if(user.getName()==null||user.getName().equals("")) {
		                	user.setNickname(nickname);
		                }
		                if(user.getSex()==null) {
		                	user.setSex(sex);
		                }
		                if(user.getPortrait()==null||user.getPortrait().equals("")) {
		                	user.setPortrait(headimgurl);
		                }
		                biz.updateUsers(user);
	                }else {
	                	user=new User();
	                	user.setNickname(nickname);
	                	user.setSex(sex);
	                	user.setPortrait(headimgurl);
	                	user.setOpenid(openId);
	                	biz.addUser(user);
	                }
	                model.addAttribute("openId", openId);
	                } catch (MalformedURLException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                } catch (IOException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                } catch (Exception e) {
						// TODO: handle exception
	                	return "login-user";
					}
	            return "tiaoUser";
	    }
	
	@GetMapping("/pcToOpenId")
	 public String pcToOpenId(String code,HttpServletResponse res,Model model) throws IOException{
	     String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx139b9e41b1b26b27&secret=bc8f1e2082e348abd68ffb77adadc4b7&code="+code+"&grant_type=authorization_code";
	     String openId="";
	            try {
	                URL getUrl=new URL(url);
	                HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                InputStream is = http.getInputStream(); 
	                int size = is.available(); 
	                byte[] b = new byte[size];
	                is.read(b);
	    
	    
	                String message = new String(b, "UTF-8");
	    
	                JSONObject json = JSONObject.parseObject(message);
	                
	                openId = json.getString("openid");
	                if(openId==null) {
	                	return "login-user";
	                }
	                String access_token=json.getString("access_token");
	                //int count=biz.updateOpenId(userId, openId);
	                url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
	                getUrl=new URL(url);
	                http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                is = http.getInputStream(); 
	                size = is.available(); 
	                b = new byte[size];
	                is.read(b);
	    
	    
	                message = new String(b, "UTF-8");
	                json = JSONObject.parseObject(message);
	                System.out.println(json.toJSONString());
	                String nickname=json.getString("nickname");
	                String headimgurl=json.getString("headimgurl");
	                Boolean sex=json.getBoolean("sex");
	                User user=biz.getById(openId);
	                if(user!=null) {
		                if(user.getName()==null||user.getName().equals("")) {
		                	user.setNickname(nickname);
		                }
		                if(user.getSex()==null) {
		                	user.setSex(sex);
		                }
		                if(user.getPortrait()==null||user.getPortrait().equals("")) {
		                	user.setPortrait(headimgurl);
		                }
		                biz.updateUsers(user);
	                }else {
	                	user=new User();
	                	user.setNickname(nickname);
	                	user.setSex(sex);
	                	user.setPortrait(headimgurl);
	                	user.setOpenid(openId);
	                	biz.addUser(user);
	                }
	                model.addAttribute("openId", openId);
	                } catch (MalformedURLException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                } catch (IOException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                }catch (Exception e) {
						// TODO: handle exception
	                	return "login-user";
					}
	            return "tiaoPC";
	    }
	
	@GetMapping("/pcToOpenIdByUser")
	 public String pcToOpenIdByUser(String code,HttpServletResponse res,Model model) throws IOException{
	     String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx139b9e41b1b26b27&secret=bc8f1e2082e348abd68ffb77adadc4b7&code="+code+"&grant_type=authorization_code";
	     String openId="";
	            try {
	                URL getUrl=new URL(url);
	                HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                InputStream is = http.getInputStream(); 
	                int size = is.available(); 
	                byte[] b = new byte[size];
	                is.read(b);
	    
	    
	                String message = new String(b, "UTF-8");
	    
	                JSONObject json = JSONObject.parseObject(message);
	                
	                openId = json.getString("openid");
	                if(openId==null) {
	                	return "login-user";
	                }
	                String access_token=json.getString("access_token");
	                //int count=biz.updateOpenId(userId, openId);
	                url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
	                getUrl=new URL(url);
	                http=(HttpURLConnection)getUrl.openConnection();
	                http.setRequestMethod("GET"); 
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	                http.setDoOutput(true);
	                http.setDoInput(true);
	    
	    
	                http.connect();
	                is = http.getInputStream(); 
	                size = is.available(); 
	                b = new byte[size];
	                is.read(b);
	    
	    
	                message = new String(b, "UTF-8");
	                json = JSONObject.parseObject(message);
	                System.out.println(json.toJSONString());
	                String nickname=json.getString("nickname");
	                String headimgurl=json.getString("headimgurl");
	                Boolean sex=json.getBoolean("sex");
	                User user=biz.getById(openId);
	                if(user!=null) {
		                if(user.getName()==null||user.getName().equals("")) {
		                	user.setNickname(nickname);
		                }
		                if(user.getSex()==null) {
		                	user.setSex(sex);
		                }
		                if(user.getPortrait()==null||user.getPortrait().equals("")) {
		                	user.setPortrait(headimgurl);
		                }
		                biz.updateUsers(user);
	                }else {
	                	user=new User();
	                	user.setNickname(nickname);
	                	user.setSex(sex);
	                	user.setPortrait(headimgurl);
	                	user.setOpenid(openId);
	                	biz.addUser(user);
	                }
	                model.addAttribute("openId", openId);
	                } catch (MalformedURLException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                } catch (IOException e) {
	                    e.printStackTrace();
	                    return "login-user";
	                }catch (Exception e) {
						// TODO: handle exception
	                	return "login-user";
					}
	            return "tiaoUserPC";
	    }
}
